package io.renren.modules.lanling.service.impl;

import io.renren.common.utils.HanyuPinyinHelper;
import io.renren.modules.lanling.entity.*;
import io.renren.modules.lanling.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;

import io.renren.modules.lanling.dao.StudentDao;
import org.springframework.transaction.annotation.Transactional;


@Service("studentService")
public class StudentServiceImpl extends ServiceImpl<StudentDao, StudentEntity> implements StudentService {

    @Autowired
    private StuSubService stuSubService;
    @Autowired
    private QuestionRecordService questionRecordService;
    @Autowired
    private ExamService examService;
    @Autowired
    private SubjectService subjectService;
    @Autowired
    private CertificateService certificateService;
    @Autowired
    private AllSubjectService allSubjectService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Query query = new Query(params);
        List<StudentEntity> studentEntityList = this.baseMapper.queryList(query);
        Integer total = this.baseMapper.queryTotal(query);

        if (studentEntityList.size() > 0) {
            Long userId;//学生id
            List<Object> subjectIds;//学生报名科目列表
            for (StudentEntity studentEntity : studentEntityList) {
                //报名科目列表
                userId = studentEntity.getUserId();
                subjectIds = stuSubService.getStudentSubjectIdList(userId);
                studentEntity.setSubjectIds(subjectIds);
            }
        }

        return new PageUtils(studentEntityList, total, query.getLimit(), query.getCurrPage());
    }


    @Override
    public StudentEntity queryObject(Long userId) {
        StudentEntity studentEntity = baseMapper.queryObject(userId);
        List<Object> subjectIds = stuSubService.getStudentSubjectIdList(userId);
        studentEntity.setSubjectIds(subjectIds);
        return studentEntity;
    }

    @Override
    public List<StudentEntity> queryList(Query query) {
        return this.baseMapper.queryList(query);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(StudentEntity studentEntity) {
        baseMapper.save(studentEntity);

        //当前报名科目列表
        List<Object> subjectIds = studentEntity.getSubjectIds();
        //
        List<Integer> allSubjectIdList = new ArrayList<>();

        HanyuPinyinHelper hanyuPinyinHelper = new HanyuPinyinHelper();

        //保存相关信息到中间表
        if (subjectIds.size() > 0) {
            for (Object obj : subjectIds) {

                StuSubEntity stuSubEntity = new StuSubEntity();
                //设置成绩
                stuSubEntity.setAvgScore(new BigDecimal(0));
                stuSubEntity.setMaxScore(new BigDecimal(0));
                stuSubEntity.setMinScore(new BigDecimal(0));

                //保存外键id
                stuSubEntity.setStudentId(studentEntity.getUserId().intValue());
                stuSubEntity.setSubjectId((int) obj);

                //设置次数
                stuSubEntity.setExamCount(0);
                stuSubEntity.setSumExamTime(0);
                stuSubEntity.setCreateDate(new Date());

                //保存对象
                stuSubService.insert(stuSubEntity);

                SubjectEntity subjectEntity = subjectService.selectById((int) obj);
                Integer allSubjectId = subjectEntity.getAllSubjectId();
                allSubjectIdList.add(allSubjectId);
            }

            //去重
            if (allSubjectIdList.size() > 0) {
                int i = 0;
                for (int j = 1; j < allSubjectIdList.size(); j++) {
                    if (allSubjectIdList.get(i).equals(allSubjectIdList.get(j))) {
                        allSubjectIdList.remove(j);
                    }
                }
            }

            String pName = hanyuPinyinHelper.toHanyuPinyin(studentEntity.getRealname());
            //新增证书列表
            for (Integer id : allSubjectIdList) {
                AllSubjectEntity allSubjectEntity = allSubjectService.selectById(id);
                String certificateName = allSubjectEntity.getCertificateName();
                CertificateEntity certificateEntity = new CertificateEntity();
                certificateEntity.setUserName(studentEntity.getRealname());
                certificateEntity.setStudentId(studentEntity.getUserId());
                certificateEntity.setStudentPname(pName);
                certificateEntity.setCertificateName(certificateName);
                certificateEntity.setSchoolId(studentEntity.getSchoolId());
                certificateEntity.setCreateDate(new Date());
                certificateEntity.setSex(studentEntity.getSex());
                certificateEntity.setIdCard(studentEntity.getIdCard());
                certificateEntity.setExamState(3);
                certificateEntity.setAllSubjectId(id);

                //真正拿到证件后，后台修改填写
                certificateEntity.setCertificateNumber(null);
                certificateEntity.setCertificateEndDate(null);
                certificateEntity.setReviewDate(null);
                certificateEntity.setExamLocation(null);
                certificateEntity.setExamTime(null);
                certificateEntity.setCompanyName(null);
                certificateService.insert(certificateEntity);
            }

        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(StudentEntity studentEntity) {

        Long studentId = studentEntity.getUserId();

        //原有的oldSubjectIds
        List<Object> oldSubjectIds = stuSubService.getStudentSubjectIdList(studentId);

        //修改后传递进来的newSubjectIds
        List<Object> newSubjectIds = studentEntity.getSubjectIds();

        //新的证件列表
        List<Integer> allSubjectIdList = new ArrayList<>();


        //todo 第一轮：遍历原有的oldSubjectIds
        if (oldSubjectIds.size() > 0) {
            for (Object obj : oldSubjectIds) {
                if (!newSubjectIds.contains(obj)) {
                    //todo 原有的科目在新的科目列表中找不到，则原有的科目就删除数据
                    EntityWrapper<StuSubEntity> entityWrapper = new EntityWrapper<>();
                    entityWrapper.eq("student_id", studentId);
                    entityWrapper.eq("subject_id", obj);
                    stuSubService.delete(entityWrapper);

                    //同步删除做题记录
                    questionRecordService.delQuestionRecordByUser((int) obj, studentId.intValue());
                    //同步删除考试记录
                    examService.delExamRecordListByUser((int) obj, studentId.intValue());
                }
            }
        }

        //todo 第二轮：遍历修改后传递进来的newSubjectIds
        if (newSubjectIds.size() > 0) {
            for (Object obj : newSubjectIds) {
                if (!oldSubjectIds.contains(obj)) {
                    //todo 新的科目在原有的科目列表中找不到，则原有的科目就新增数据
                    StuSubEntity stuSubEntity = new StuSubEntity();
                    stuSubEntity.setStudentId(studentId.intValue());
                    stuSubEntity.setSubjectId((int) obj);
                    //设置成绩
                    stuSubEntity.setMaxScore(new BigDecimal(0));
                    stuSubEntity.setMinScore(new BigDecimal(0));
                    stuSubEntity.setAvgScore(new BigDecimal(0));
                    //设置次数和日期
                    stuSubEntity.setExamCount(0);
                    stuSubEntity.setSumExamTime(0);
                    stuSubEntity.setCreateDate(new Date());
                    //保存当前对象
                    stuSubService.insert(stuSubEntity);
                }
                SubjectEntity subjectEntity = subjectService.selectById((int) obj);
                Integer allSubjectId = subjectEntity.getAllSubjectId();
                allSubjectIdList.add(allSubjectId);
            }
        }

        //去重
        if (allSubjectIdList.size() > 0) {
            int i = 0;
            for (int j = 1; j < allSubjectIdList.size(); j++) {
                if (allSubjectIdList.get(i).equals(allSubjectIdList.get(j))) {
                    allSubjectIdList.remove(j);
                }
            }
        }

        //处理证书
        certificateService.dealWithCert(allSubjectIdList, studentEntity);


        baseMapper.update(studentEntity);
    }

}
